    //
//  ICEPageViewController.m
//  ICEViewPrototype
//
//  Created by Aurélien Ammeloot on 23/07/2010.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ICEPageViewController.h"
#import "ICEStory.h"
#import "ICEFullScreenTextVC.h"
#import "ICEFullImageViewController.h"

#define BOTTOM_BAR_HEIGHT 21.

@interface ICEPageViewController () <UIScrollViewDelegate, UIWebViewDelegate, ICEFullScreenTextVCDelegate, ICEFullImageViewControllerDelegate>


- (void)_updateStory;
- (void)_showFullScreenText:(NSString *)ident;
- (void)_showFullImage:(NSString *)ident;


@end


@implementation ICEPageViewController
@synthesize detailViewController = _detailViewController;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
	_pages = [[NSMutableArray alloc] init];

    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)_updateStory
{
	if(_alredayLoaded == nil) {
		_alredayLoaded = [[NSMutableArray alloc] init];
	}
	if([_alredayLoaded count] > 0) {
		[_alredayLoaded removeAllObjects];
	}
	
	if (_pages == nil) {
		_pages = [[NSMutableArray alloc] init];
	}
	if ([_pages count] > 0) {
		[_pages removeAllObjects];
	}
	
	_pageNumber = _story.length;
	_pageControl.numberOfPages =_story.length;
	_pageControl.currentPage = 0;
	
	_pageControlUsed = NO;
	
	// Set the content size according to the number of pages
	_scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * _pageNumber, _scrollView.frame.size.height);
	
	// Allocating the array of webviews
	_pages = [[NSMutableArray alloc] init];
	
	// Pages added to the array and the scroll view
	for(int i=0; i<_pageNumber;i++) {
		UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(i*self.view.bounds.size.width, 0., self.view.bounds.size.width, self.view.bounds.size.height - BOTTOM_BAR_HEIGHT)];
		// NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"page%d",i+1] ofType:@"html" inDirectory:_story.baseFolder];
		webView.delegate = self;
		webView.tag = i;
		NSString *path = [_story.baseFolder stringByAppendingFormat:@"/page%d.html",i+1];
		
		NSString *htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
		[webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:path]];
		[_pages addObject:webView];
		[_alredayLoaded addObject:[NSNumber numberWithBool:NO]];
		[_scrollView addSubview:webView];
		[webView release];
	}
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[_pages release];
    [super dealloc];
}

#pragma mark -
#pragma mark UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
	//ignore if initiated by the page control
	if(_pageControlUsed)
		return;
	
	// Switch page control indicator around 50%
	CGFloat pageWidth = scrollView.frame.size.width;
	int page = floor((scrollView.contentOffset.x - pageWidth/2) / pageWidth) + 1;
	_pageControl.currentPage = page;
	
	
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
	_pageControlUsed = NO;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
	_pageControlUsed = NO;
}



#pragma mark -
#pragma mark UIPageControl event handling

- (IBAction)pageControlDidChange:(id)sender
{
	int page = _pageControl.currentPage;
	
	// Update Scrollview
	CGRect frame = _scrollView.frame;
	frame.origin.x = frame.size.width * page;
	frame.origin.y = 0;
	[_scrollView scrollRectToVisible:frame animated:YES];
	
	_pageControlUsed = YES;
}


#pragma mark -
#pragma mark Orientation changes handling

- (void)updateOrientation
{
	// Set the content size according to the number of pages
	_scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * _pageNumber, _scrollView.frame.size.height);

	for (int i=0; i<_pageNumber; i++) {
		UIWebView *webView = (UIWebView *)[_pages objectAtIndex:i];
		webView.frame = CGRectMake(i*self.view.bounds.size.width, 0., self.view.bounds.size.width, self.view.bounds.size.height - BOTTOM_BAR_HEIGHT);
		_scrollView.contentOffset = CGPointZero;
	}
}

#pragma mark -
#pragma mark story get/set

- (ICEStory *)story
{
	return _story;
}

- (void)setStory:(ICEStory *)story
{
	if (_story != nil) {
		[_story release];
	}
	_story = [story retain];
	[self _updateStory];
}

#pragma mark -
#pragma mark UIWebViewDelegate methods

// Used to override the requests -- Extract elements
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
	// Dev only -> if first time, then let it load
	if([[_alredayLoaded objectAtIndex:webView.tag] boolValue] == NO) {
		[_alredayLoaded replaceObjectAtIndex:webView.tag withObject:[NSNumber numberWithBool:YES]];
		return YES;
	}
	
	NSString *urlString = [[request URL] absoluteString];
	//	NSLog(@"Received URL: %@",urlString);
	//	NSLog(@"Navigation type: %d",navigationType);
	
	// Extracting substrings from the URL
	NSArray *substrings = [urlString componentsSeparatedByString:@"ICEQUERY."];
	//	NSLog(@"The substrings: %@",substrings);
	
	// Extracting substrings, again
	substrings = [[substrings objectAtIndex:1] componentsSeparatedByString:@"."];
	NSString *type = [substrings objectAtIndex:0];
	NSString *ident = [substrings objectAtIndex:1];
	
	if([type isEqualToString:@"text"]) {
		[self performSelector:@selector(_showFullScreenText:) withObject:ident afterDelay:0];
	}
	if ([type isEqualToString:@"image"]) {
		[self performSelector:@selector(_showFullImage:) withObject:ident afterDelay:0];
	}
	
	return NO;
}

#pragma mark -
#pragma mark Opening full screen views

- (void)_showFullImage:(NSString *)ident
{
	ICEFullImageViewController *fullImageViewController = [[ICEFullImageViewController alloc] initWithNibName:@"ICEFullImageViewController" bundle:[NSBundle mainBundle]];
	fullImageViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	fullImageViewController.modalPresentationStyle = UIModalPresentationFullScreen;
	fullImageViewController.delegate = self;
	
	[self.detailViewController presentModalViewController:fullImageViewController animated:YES];
	
	NSLog(@"_showFullImage:%@",ident);
}

- (void)_showFullScreenText:(NSString *)ident
{
	ICEFullScreenTextVC *fullScreenTextVC = [[ICEFullScreenTextVC alloc] initWithNibName:@"ICEFullScreenTextVC" bundle:[NSBundle mainBundle]];
	fullScreenTextVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	fullScreenTextVC.modalPresentationStyle = UIModalPresentationFullScreen;
	fullScreenTextVC.delegate = self;
	
	[self.detailViewController presentModalViewController:fullScreenTextVC animated:YES];
	
	NSLog(@"_showFullScreenText:%@",ident);
}

#pragma mark -
#pragma mark ICEFullScreenTextVC ICEFullImageViewController Delegates

- (void)fullScreenTextVCRequestsDismissal:(ICEFullScreenTextVC *)fullScreenTextVC
{
	[self.detailViewController dismissModalViewControllerAnimated:YES];
	[fullScreenTextVC release];
	
}

- (void)fullImageViewControllerDidRequestDismissal:(ICEFullImageViewController *)fullImageViewController;
{
	[self.detailViewController dismissModalViewControllerAnimated:YES];
	[fullImageViewController release];
}



@end
